import { Button, Card, DatePicker, Typography, Flex, Spin, message } from 'antd'
import { ExportOutlined } from '@ant-design/icons'
import icon from '@/assets/images/enterprise/icon@2x.png'
import BarChart from '@/components/BarChart'
import { useState, useEffect } from 'react'
import dayjs from 'dayjs'
import { settlementAPI, exportgenerateAPI } from '@/apis'
import axios from 'axios'
import _ from 'lodash'
const { Paragraph, Title, Text } = Typography
const { RangePicker } = DatePicker
const xAxisData = ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06', '2024-07']

export default function Jiesuanpianhao({ data }) {
    const chartBoxH = 360;
    const [startDate, setStartDate] = useState(dayjs().startOf('year').format('YYYY-MM-DD'))
    const [endDate, setEndDate] = useState(dayjs(new Date()).format('YYYY-MM-DD'))
    // const [startDate, setStartDate] = useState('2024-01-01')
    // const [endDate, setEndDate] = useState('2024-12-31')
    const [isloading, setisloading] = useState(false)
    const handleDate = (time) => {
        setStartDate(dayjs(time[0]).format('YYYY-MM-DD'))
        setEndDate(dayjs(time[1]).format('YYYY-MM-DD'))
    }
    const [xAxisData, setxAxisData] = useState(null)
    const [statisticsData, setstatisticsData] = useState(null)
    const [indicator, setindicator] = useState({})
    const [messageApi, contextHolder] = message.useMessage();
    useEffect(() => {
        function getData() {
            setisloading(true)
            settlementAPI({
                company: data.company_info[0].GSMC,
                companytype: data.company_info[0].IS_CYDW,
                startDate,
                endDate
            }).then(res => {
                setindicator(res.data.jyzb)
                if (res.data.jstj.months.length > 0) {
                    setxAxisData(res.data.jstj.months.map(item => startDate.split('-')[0] + '-' + item))
                    const pjdata = res.data.jstj.pj_y_je_list.map(item => _.round(item.value, 2))
                    const xjdata = res.data.jstj.xj_y_je_list.map(item => _.round(item.value, 2))
                    setstatisticsData({
                        yName: '交易金额(万元)',
                        data: [
                            {
                                name: '票据结算',
                                data: pjdata
                            },
                            {
                                name: '现金结算',
                                data: xjdata
                            }
                        ]
                    })
                    setisloading(false)
                }
            })
        }
        getData()
    }, [data, startDate, endDate])
    const report_download = () => {
        // setFlowLoading(true)
        // 生成报告
        exportgenerateAPI({
            company: data.company_info[0].GSMC,
        }).then(res => {
            if (res.code == 200) {
                messageApi.open({
                    type: 'success',
                    content: res.message,
                });
                axios.get(`http://192.168.1.182:9000/kshx/download-file?uuid=${res.data}`, {
                    responseType: 'blob', 
                    headers: {
                        Authorization: 'Bearer ' + localStorage.getItem('kshxtoken')
                    }
                }).then(res => {
                    const blob = new Blob([res.data], { type: res.headers['content-type'] });
                    let fileName = data.company_info[0].GSMC + '.docx'; // 默认名
                    // 创建下载链接并触发下载
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                }).catch(err => {
                    console.error('文件下载失败:', err);
                });
            }else{
                messageApi.open({
                    type: 'error',
                    content: res.message,
                });
            }
        }).catch(()=>{
            messageApi.open({
                type: 'error',
                content: '报告生成失败！',
            });
        }).finally(() => {
            // setFlowLoading(false)
        })
    }
    return (
        <Spin tip="页面加载中..." spinning={isloading} size='large'>
            <div className='rival-container'>
                <Flex justify='center' className='title'>
                    <Title level={3}>{data.company_info[0].GSMC}</Title>
                    {contextHolder}
                    <Button className='btn' type='link' icon={<ExportOutlined />} onClick={report_download}>导出报告</Button>
                </Flex>
                <Flex justify='center' style={{ marginTop: '14px' }}>
                    <RangePicker onChange={handleDate} defaultValue={[dayjs(startDate, 'YYYY-MM-DD'), dayjs(endDate, 'YYYY-MM-DD')]}></RangePicker>
                    {/* <DatePicker onChange={handleDate} defaultValue={dayjs('2024', 'YYYY')} picker="year" /> */}
                </Flex>
                <Card className='indicator-wrap'>
                    <Flex>
                        <Flex align='center'>
                            <img src={icon} style={{ width: '22px', marginRight: '8px' }} alt='' />
                            <Title level={5}>交易指标</Title>
                        </Flex>
                    </Flex>
                    {
                        indicator.avg_month && indicator.js_like ?
                            <Paragraph className='desc'>该企业结算方式以 <Text strong>{indicator.js_method}</Text> 为主，占所有交易总额 <Text strong>{indicator.jy_ratio}</Text>。票据周转时间平均 <Text strong>{indicator.avg_month}个月</Text> 。其中偏好 <Text strong>{indicator.js_like}</Text> 结算。</Paragraph>
                            : <Paragraph className='desc'>该企业结算方式以 <Text strong>{indicator.js_method}</Text> 为主，占所有交易总额 <Text strong>{indicator.jy_ratio}</Text>。</Paragraph>
                    }
                </Card>
                <Card style={{ border: 'none' }}>
                    <Title level={5}>结算统计</Title>
                    <div className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                        {xAxisData && <BarChart xAxisData={xAxisData} data={statisticsData} />}
                    </div>
                </Card>
            </div>
        </Spin>
    )
}
